package jvm;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

public class Test2 extends Thread{

    private Exchanger<String> exchanger;
    private String string;
    private String threadName;

    public Test2(Exchanger<String> exchanger, String string,
                         String threadName) {
        this.exchanger = exchanger;
        this.string = string;
        this.threadName = threadName;
    }

    public void run() {
        try {
            System.out.println(threadName + ": " + exchanger.exchange(string));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Exchanger<String> exchanger = new Exchanger<>();
        Test2 test1 = new Test2(exchanger, "信息一",
                "线程一");
        Test2 test2 = new Test2(exchanger, "信息二",
                "线程二");

        test1.start();
        test2.start();

        TimeUnit.SECONDS.sleep(2);

        Test2 test3 = new Test2(exchanger, "信息三",
                "线程三");
        //线程三进去,卡在exchanger.exchange()等待其他线程与其进行交换
        test3.start();

        String s = exchanger.exchange("主线程信息");
        System.out.println(s);
    }

}
